package com.qyhl.webtv.module_news.news.collect;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.module_news.utils.view.RecyclerViewImplementsContextMenu;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/5.
 * 收藏界面
 */

@Route(path = ARouterPathConstant.COLLECT, extras = ARouterPathConstant.LOGIN_NEEDED)
public class CollectActivity extends BaseActivity implements CollectContract.CollectView {
    @BindView(R2.id.listview)
    RecyclerViewImplementsContextMenu listview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private LoadingDialog.Builder builder;

    private String pageId = "0";//分页Id

    private CollectPresenter mPresenter;

    private List<GlobalNewsBean> indexList;
    private List<GlobalNewsBean> mDataList;

    private MultiItemTypeAdapter mAdapter;
    private boolean hasPicture;//是否是无图

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_collect;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new CollectPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getData(pageId);
    }


    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();

        BusFactory.getBus().register(this);
        //刷新配置
        refresh.setEnableLoadMore(true);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setDisableContentWhenRefresh(true);
        refresh.setDisableContentWhenLoading(true);


        builder = new LoadingDialog.Builder(CollectActivity.this);
        builder.setTitle("处理中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(this, R.color.global_gray_lv4)));
        //初始化适配器
        mAdapter = new MultiItemTypeAdapter(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemUnion(this));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        listview.setAdapter(mAdapter);
        //为ListView注册ContextMenu
        registerForContextMenu(listview);

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                GlobalNewsBean bean = mDataList.get(position);
                ItemSkipUtils.getInstance().itemSkip(bean, CollectActivity.this);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }

    /**
     * 监听
     */
    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(refreshlayout -> {
            pageId = "0";
            mPresenter.getData(pageId);
        });

        //加载
        refresh.setOnLoadMoreListener(refreshlayout -> mPresenter.getData(pageId));

        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            pageId = "0";
            mPresenter.getData(pageId);
        });

        backBtn.setOnClickListener(v -> finish());


        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

        listview.setOnCreateContextMenuListener((menu, v, menuInfo) -> menu.add(0, 0, 0, "取消收藏"));

    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case 0:
                mPresenter.cancelCollect(mDataList.get(menuInfo.position).getNewsId());
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 设置收藏数据
     *
     * @param beanList
     */
    @Override
    public void setDatas(List<NewsBean> beanList, boolean isMore) {
        refresh.finishRefresh();
        refresh.finishLoadMore();

        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        indexList = new ArrayList<>();
        int globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
        int globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
        //全局新闻样式配置
        for (int i = 0; i < beanList.size(); i++) {
            if ("2".equalsIgnoreCase(beanList.get(i).getType())) {
                beanList.get(i).setCommonStyle(globalCommon);
                beanList.get(i).setVideoStyle(globalVideo);
            }
        }
        if (beanList.size() > 0) {
            pageId = beanList.get(beanList.size() - 1).getZccollectID();
        } else {
            pageId = "-1";
            return;
        }
        //数据模型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    switch (bean.getPluralPicsFlag()) {
                        case 0:
                            style = bean.getCommonStyle();
                            break;
                        case 1://三图
                            hasPicture = false;
                            if (bean.getImagess().size() == 1) {
                                hasPicture = true;
                                pOne = bean.getImagess().get(0).getImageUrlString();
                            } else if (bean.getImagess().size() == 2) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                hasPicture = true;
                            } else if (bean.getImagess().size() >= 3) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                pThree = bean.getImagess().get(2).getImageUrlString();
                                hasPicture = true;
                            } else {
                                hasPicture = false;
                            }
                            style = 4;
                            break;
                        case 2:
                            style = 3;
                            break;
                        default:
                            style = bean.getCommonStyle();
                            break;
                    }
                    break;
                case "2"://图片新闻
                    type = "2";
                    if (bean.getImagess().size() == 1) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() == 2) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() >= 3) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        pThree = bean.getImagess().get(2).getImageUrlString();
                        hasPicture = true;
                    } else {
                        hasPicture = false;
                    }
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }

        //更新数据源
        if (isMore) {
            mDataList.addAll(indexList);
        } else {
            mDataList.clear();
            mDataList.addAll(indexList);
        }

        mAdapter.notifyDataSetChanged();
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setLog(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Log.i("info_collect", msg);
    }

    @Override
    public void cancelCollectSuccess() {
        builder.dismiss();
        pageId = "0";
        mPresenter.getData(pageId);
    }

    @Override
    public void cancelCollectError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg).show();
    }

    @Override
    public void cancelCollect() {
        builder.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.CollectMessage event) {
        if (event != null) {
            pageId = "0";
            mPresenter.getData(pageId);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("资讯收藏");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("资讯收藏");

        MobclickAgent.onPause(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
        unregisterForContextMenu(listview);
    }


}
